<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { useTable } from '@/hooks/web/useTable'
import { Dialog } from '@/components/Dialog'
import { ref, unref, reactive, h } from 'vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import GetSystemDictApi from '@/api/dictionary/index'
import { ElTag } from 'element-plus'
import * as XLSX from 'xlsx'
import { useRouter } from 'vue-router'
import { Icon } from '@/components/Icon'
import EditDictType from './components/EditDictType.vue'
const { push } = useRouter()
const ids = ref<string[]>([])
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await GetSystemDictApi.dictType({
      pageNum: String(unref(currentPage)),
      pageSize: String(unref(pageSize)),
      ...unref(searchParams)
    })
    return {
      list: res.rows,
      total: res.total
    }
  },
  fetchDelApi: async () => {
    const res = await GetSystemDictApi.DeletdictType(unref(ids)[0])
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}
const { t } = useI18n()
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'dictId',
    label: t('字典编号'),
    // type: "dictId",
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'dictName',
    label: t('字典名称'),
    search: {
      hidden: false,
      component: 'Input',
      componentProps: {
        placeholder: '字典名称'
      }
    },
    form: {
      component: 'Input',
      colProps: {
        span: 20
      }
    }
  },
  {
    field: 'dictType',
    label: t('字典类型'),
    search: {
      hidden: false,
      component: 'Input',
      componentProps: {
        placeholder: '字典类型'
      }
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <span class="TableBtn" onClick={() => action(data.row, 'dictType')}>
                {data.row.dictType}
              </span>
            </>
          )
        }
      }
    },
    form: {
      component: 'Input',
      colProps: {
        span: 20
      }
    }
  },
  {
    field: 'status',
    label: t('状态'),
    search: {
      hidden: false,
      component: 'Select',
      componentProps: {
        placeholder: '状态',
        options: [
          {
            label: '正常',
            value: '0'
          },
          {
            label: '停用',
            value: '1'
          }
        ]
      }
    },
    formatter: (_: Recordable, __: any, cellValue: number) => {
      return h(
        ElTag,
        {
          type: cellValue == 0 ? 'primary' : 'danger'
        },
        () => (cellValue == 0 ? t('正常') : t('停用'))
      )
    },
    form: {
      component: 'RadioGroup',
      componentProps: {
        options: [
          {
            label: '正常',
            value: '0'
          },
          {
            label: '停用',
            value: '1'
          }
        ]
      }
    }
  },
  {
    field: 'remark',
    label: t('备注'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      colProps: {
        span: 20
      },
      componentProps: {
        type: 'textarea',
        rows: 3
      }
    }
  },
  {
    field: 'createTime',
    label: t('创建时间'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'action',
    width: '150px',
    label: t('操作'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <span
                class="TableBtn"
                style="font-weight: 600;"
                onClick={() => action(data.row, 'edit')}
              >
                {t('修改')}
              </span>
              <span
                class="TableBtn"
                style="font-weight: 600;color:#f56c6c"
                onClick={() => delData(data.row)}
              >
                {t('删除')}
              </span>
            </>
          )
        }
      }
    }
  }
])
// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)
const dialogVisible = ref(false)
const currentRow = ref({})
const delLoading = ref(false)
const dialogTitle = ref('')
const actionType = ref('')
//删除轨迹
const delData = async (row: any) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.dictId] : elTableExpose?.getSelectionRows().map((v: any) => v.dictId) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}
//表格操作
const action = (row: any, type: string) => {
  actionType.value = type
  if (type == 'dictType') {
    push({ path: '/authorization/dictData', query: { dictType: row.dictType } })
  } else if (type == 'edit') {
    dialogTitle.value = '修改字典类型'
    currentRow.value = row
    dialogVisible.value = true
  } else {
    dialogTitle.value = '新增字典类型'
    dialogVisible.value = true
  }
}
//修改字典类型Ref
const EditDictTypeRef = ref<any>()
const saveLoading = ref(false)
//修改提交
const save = async () => {
  const write = unref(EditDictTypeRef)
  const formData = await write?.submit()
  console.log(formData)
  if (formData) {
    saveLoading.value = true
    saveLoading.value = false
    const res: any = ref(false)
    console.log(actionType.value)
    //新增字典类型
    if (actionType.value == 'add') {
      res.value = await GetSystemDictApi.AdddictType(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
    } else if (actionType.value == 'edit') {
      //修改字典类型
      res.value = await GetSystemDictApi.EditdictType(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
    }
    if (res.value) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
    }
  }
}

//导出表格为excel
const ExportData = () => {
  new Promise((resolve) => {
    pageSize.value = unref(total)
    resolve(tableState)
  }).then(() => {
    const workbook = XLSX.utils.book_new()
    //在table上建立的id属性
    const ws1 = XLSX.utils.table_to_sheet(document.getElementById('table'))
    XLSX.utils.book_append_sheet(workbook, ws1, 'Sheet1')
    XLSX.writeFile(workbook, `字典信息.xlsx`)
  })
}
</script>

<template>
  <ContentWrap style="position: relative">
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />
    <BaseButton type="success" class="AddbtnStyle" size="small" plain @click="action({}, 'add')">
      <Icon icon="ep:plus" :size="12" />新增
    </BaseButton>
    <BaseButton type="warning" class="AddbtnStyle" size="small" plain @click="ExportData">
      <Icon icon="ep:download" :size="12" />导出
    </BaseButton>
    <Table
      id="table"
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <EditDictType
      ref="EditDictTypeRef"
      :form-schema="allSchemas.formSchema"
      :current-row="currentRow"
      :tital="dialogTitle"
    />
    <template #footer>
      <BaseButton type="primary" :loading="saveLoading" @click="save">
        {{ t('提交') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('关闭') }}</BaseButton>
    </template>
  </Dialog>
</template>
<style scope>
.TableBtn {
  margin: 0 5px;
  cursor: pointer;
  color: #409eff;
  font-size: 12px;
  /* font-weight: 600; */
}
.AddbtnStyle {
  margin-bottom: 18px;
  margin-right: 10px;
}
</style>
